package com.hmyd.hmyd_android.adapter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.dto.GoodDetails;
import com.hmyd.hmyd_android.utils.MyToast;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;

public class ShopCarAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private List<GoodDetails> datas;
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private int number = 0;
	private TextView mTvNeedPay;
	private ImageView mIvEmpty;
	private View content;
	private RelativeLayout bottomLayout;
	private Context mContext;
	private BitmapUtils bitmapUtils;
	private List<GoodDetails> checkedGoods; // 被选择的商品
	private long needPay = 0;
	private TextView home_right;

	public ShopCarAdapter(Context context, List<GoodDetails> goodDetails,
			TextView textView, ImageView imageView, View content,
			RelativeLayout bottomLayout,TextView home_right) {
		this.datas = goodDetails;
		mInflater = LayoutInflater.from(context);

		sharedPreferences = context.getSharedPreferences("test",
				Activity.MODE_PRIVATE);
		editor = sharedPreferences.edit();
		this.mTvNeedPay = textView;
		this.mIvEmpty = imageView;
		this.content = content;
		this.bottomLayout = bottomLayout;
		this.mContext = context;
		this.home_right = home_right;
		checkedGoods = new ArrayList<GoodDetails>();
		bitmapUtils = AppBasic.getBitmapUtils(context);
	}

	@Override
	public int getCount() {
		return datas != null ? datas.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return datas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * 获取被选中的商品
	 * 
	 * @return
	 */
	public List<GoodDetails> getCheckedGoods() {
		return checkedGoods;
	}

	/**
	 * 清空选择菜单
	 */
	public void setCheckedGoodsToNull() {
		checkedGoods.clear();
		notifyDataSetChanged();
	}
	
	/**
	 * 选中所有商品,并返回
	 */
	public List<GoodDetails> checkAllItem() {
		checkedGoods.clear();
		if(datas != null && datas.size() > 0) {
			checkedGoods.addAll(datas);
			notifyDataSetChanged();
		}
		return checkedGoods;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.view_shop_cart_item, null);
			holder = new ViewHolder();

			holder.mIvPic = (ImageView) convertView
					.findViewById(R.id.shopcart_pic);
			holder.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
			holder.mTvScore = (TextView) convertView
					.findViewById(R.id.tv_price);
			holder.mTvItemNum = (TextView) convertView
					.findViewById(R.id.tv_item_num);
			// holder.mTvNum = (TextView)
			// convertView.findViewById(R.id.shopcart_pic_num);
			holder.mIBtnDel = (ImageButton) convertView
					.findViewById(R.id.ib_del);
			holder.mIbJia = (Button) convertView.findViewById(R.id.ib_jia);
			holder.mIbJian = (Button) convertView.findViewById(R.id.ib_jian);
			holder.line = convertView.findViewById(R.id.line);
			holder.gouwuCheck = (CheckBox) convertView
					.findViewById(R.id.gouwuCheck);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final GoodDetails item = datas.get(position);

		holder.mTvName.setText(item.title);
		holder.mTvScore.setText(item.presentPrice + "");
		holder.mTvItemNum.setText(item.number + "");
		// holder.mTvNum.setText("X" + item.number);

		holder.mIvPic.setTag(item.icon);
		// 通过 tag 来防止图片错位
		if (holder.mIvPic.getTag() != null
				&& holder.mIvPic.getTag().equals(item.icon)) {
			// ImageLoader.getInstance().displayImage(item.icon.get(0),
			// holder.mIvPic);
			// xutils自带的图片缓存机制
			bitmapUtils.display(holder.mIvPic, item.icon.get(0));
		}

		holder.mIbJia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				number = item.number;
				if (number >= item.stock) {
					MyToast.showHMToast((Activity) mContext, false, "库存不足");
					return;
				}
				if (number >= 20) {
					MyToast.showHMToast((Activity) mContext, false,
							"您每次最多只能换购20件商品");
					return;
				}
				number = number + 1;
				holder.mIbJian.setEnabled(true);
				holder.mTvItemNum.setText(number + "");
				item.number = number;
				// needPay = needPay+item.presentPrice;
				try {
					List2String(datas);
				} catch (IOException e) {
					e.printStackTrace();
				}
				needPay = 0;
				for (GoodDetails goodDetails : checkedGoods) {
					needPay = needPay + goodDetails.number
							* goodDetails.presentPrice;
				}
				mTvNeedPay.setText(needPay + "");
			}
		});

		holder.mIbJian.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				number = item.number;
				if (number > 1) {
					number--;
					// holder.mTvNum.setText("X" + number);
					holder.mTvItemNum.setText(number + "");
					item.number = number;
					try {
						List2String(datas);
					} catch (IOException e) {
						e.printStackTrace();
					}
					needPay = 0;
					for (GoodDetails goodDetails : checkedGoods) {
						needPay = needPay + goodDetails.number
								* goodDetails.presentPrice;
					}
					mTvNeedPay.setText(needPay + "");
				}
			}
		});

		holder.mIBtnDel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				datas.remove(position);
				if (datas.size() == 0) {
					mIvEmpty.setVisibility(View.VISIBLE);
					content.setVisibility(View.GONE);
					bottomLayout.setVisibility(View.GONE);
					home_right.setVisibility(View.GONE);
				} else {
					mIvEmpty.setVisibility(View.GONE);
					content.setVisibility(View.VISIBLE);
					bottomLayout.setVisibility(View.VISIBLE);
					home_right.setVisibility(View.VISIBLE);
				}
				boolean deleteFlag = false;
				try {
					List2String(datas);
				} catch (IOException e) {
					e.printStackTrace();
				}
				needPay = 0;
				for (GoodDetails goodDetails : checkedGoods) {
					needPay = needPay + goodDetails.number
							* goodDetails.presentPrice;
					if (goodDetails.id.equals(item.id)) {
						deleteFlag = true;
					}
				}
				if (deleteFlag) {
					checkedGoods.remove(item);
				}
				mTvNeedPay.setText(needPay + "");
				notifyDataSetChanged();
			}
		});

		// 购物车选择事件
		holder.gouwuCheck
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							if (!checkedGoods.contains(item)) {
								checkedGoods.add(item);
							}
						} else {
							if (checkedGoods.contains(item)) {
								checkedGoods.remove(item);
							}
						}
						needPay = 0;
						for (GoodDetails goodDetails : checkedGoods) {
							needPay = needPay + goodDetails.number
									* goodDetails.presentPrice;
						}
						mTvNeedPay.setText(needPay + "");
					}
				});
		needPay = 0;
		for (GoodDetails goodDetails : checkedGoods) {
			needPay = needPay + goodDetails.number * goodDetails.presentPrice;
		}
		mTvNeedPay.setText(needPay + "");

		if (position == datas.size() - 1) {
			holder.line.setVisibility(View.INVISIBLE);
		} else {
			holder.line.setVisibility(View.VISIBLE);
		}
		String tag = item.id.replace("[^\\w]", "").trim();
		holder.gouwuCheck.setTag(tag);
		if (holder.gouwuCheck.getTag() != null
				&& holder.gouwuCheck.getTag().equals(tag)) {
			if (checkedGoods.contains(item)) {
				holder.gouwuCheck.setChecked(true);
			} else {
				holder.gouwuCheck.setChecked(false);
			}
		}

		return convertView;
	}

	class ViewHolder {
		ImageButton mIBtnDel;
		Button mIbJia;
		Button mIbJian;
		TextView mTvName;
		TextView mTvScore;
		// TextView mTvNum;
		TextView mTvItemNum;
		ImageView mIvPic;
		View line;
		CheckBox gouwuCheck;
	}

	/**
	 * list转换成string
	 * 
	 * @param datas2
	 */
	private void List2String(List<GoodDetails> datas) throws IOException {

		// 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 然后将得到的字符数据装载到ObjectOutputStream
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				byteArrayOutputStream);
		// writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
		objectOutputStream.writeObject(datas);
		// 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
		String ListString = new String(Base64.encode(
				byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
		// 关闭objectOutputStream
		objectOutputStream.close();

		editor.putString("data", "");
		// 用putString的方法保存数据
		editor.putString("data", ListString);
		// 提交当前数据
		editor.commit();
	}

	public List<GoodDetails> String2List(String ListString)
			throws StreamCorruptedException, IOException,
			ClassNotFoundException {
		byte[] mobileBytes = Base64.decode(ListString.getBytes(),
				Base64.DEFAULT);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				mobileBytes);
		ObjectInputStream objectInputStream = new ObjectInputStream(
				byteArrayInputStream);
		@SuppressWarnings("unchecked")
		List<GoodDetails> carList = (List<GoodDetails>) objectInputStream
				.readObject();

		datas.addAll(carList);
		List2String(datas);
		objectInputStream.close();
		return carList;
	}

}
